package org.hank.compose_yyzs.ui.widget.dialog

import android.view.Gravity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.orhanobut.logger.Logger
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.ui.destinations.TipsDialogDestination
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.utils.getString
import org.hank.compose_yyzs.viewmodel.WifiSetViewModel
import org.hank.compose_yyzs.viewmodel.WifiSettingEvent

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/8/28 10:51
 *描述:
 */

@Composable
fun BottomWifiSettingDialog(
    showState: MutableState<Boolean>,
    navigator: DestinationsNavigator,
    onWifiUpdateClick : ()->Unit = {},
    onCancelClick: () -> Unit = {}
) {
    val viewModel: WifiSetViewModel = hiltViewModel()
    LaunchedEffect(key1 = Unit) {
        viewModel.viewEvents.collect {
            if (it is WifiSettingEvent.ErrorMessage) {
                Logger.d("get Message From viewmodel ${it.message}")
                navigator.navigate(TipsDialogDestination(it.message))
            }
        }
    }
    DialogLikeBottomSheet(
        showState = showState,
        dismissRequest = {
            onCancelClick.invoke()
        }) {
        var textWifiName = viewModel.wifiName.collectAsStateWithLifecycle()
        var textWifiPass = viewModel.wifiPass.collectAsStateWithLifecycle()
        var textWifiIp1 = viewModel.wifiIp1.collectAsStateWithLifecycle()
        var textWifiIp2 = viewModel.wifiIp2.collectAsStateWithLifecycle()
        var textWifiIp3 = viewModel.wifiIp3.collectAsStateWithLifecycle()
        var textWifiIp4 = viewModel.wifiIp4.collectAsStateWithLifecycle()
        var isWifiHistoryFlag = remember { mutableStateOf(false) }
        var scope = rememberCoroutineScope()
        var focusManager = LocalFocusManager.current
        Column {
            Spacer(modifier = Modifier.height(16.dp))
            Box(
                modifier = Modifier
                    .padding(bottom = 16.dp)
                    .fillMaxWidth()
            ) {
                Text(
                    text = getString(R.string.setting_wifi),
                    style = MaterialTheme.typography.titleMedium.copy(),
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.align(Alignment.Center),
                    textAlign = TextAlign.Center
                )
                Image(
                    painter = painterResource(id = R.mipmap.ic_cross_x),
                    contentDescription = "",
                    modifier = Modifier
                        .align(
                            Alignment.CenterEnd
                        )
                        .padding(end = 24.dp)
                        .clickable {
                            it.invoke()
                        }
                )
            }
            Divider(color = AppTheme.colors.divider, thickness = 1.dp)
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(intrinsicSize = IntrinsicSize.Min)
                    .padding(16.dp),
                verticalAlignment = CenterVertically
            ) {
                Text(
                    text = getString(resourceId = R.string.setting_wifi_name),
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.width(80.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                BasicTextField(
                    value = textWifiName.value,
                    singleLine = true,
                    onValueChange = {
                        scope.launch {
                            viewModel.wifiName.emit(it)
                        }
                    },
                    modifier = Modifier
                        .weight(1f)
                        .onFocusChanged {
                            scope.launch { viewModel.wifiNameFocus.emit(it.hasFocus) }
                        },
                    keyboardOptions = KeyboardOptions.Default.copy(
                        keyboardType = KeyboardType.Email,
                        imeAction = ImeAction.Next
                    ),
                    keyboardActions = KeyboardActions(onNext = {
                        focusManager.moveFocus(focusDirection = FocusDirection.Next)
                    }),
                    decorationBox = {
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(4.dp)
                        ) {
                            if (textWifiName.value.isEmpty() && !viewModel.wifiNameFocus.collectAsStateWithLifecycle().value) {
                                Text(
                                    text = getString(resourceId = R.string.setting_wifi_name_hint),
                                    style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary)
                                )
                            } else
                                it.invoke()
                        }
                    }
                )
            }

            Divider(color = AppTheme.colors.divider, thickness = 1.dp)
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(intrinsicSize = IntrinsicSize.Min)
                    .padding(16.dp),
                verticalAlignment = CenterVertically
            ) {
                Text(
                    text = getString(resourceId = R.string.setting_wifi_pass),
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.width(80.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                BasicTextField(
                    value = textWifiPass.value,
                    singleLine = true,
                    onValueChange = {
                        scope.launch {
                            viewModel.wifiPass.emit(it)
                        }
                    },
                    modifier = Modifier
                        .weight(1f)
                        .onFocusChanged { it ->
                            scope.launch {
                                viewModel.wifiPassFocus.emit(it.hasFocus)
                            }
                        },
                    keyboardOptions = KeyboardOptions.Default.copy(
                        keyboardType = KeyboardType.Email,
                        imeAction = ImeAction.Next
                    ),
                    keyboardActions = KeyboardActions(onNext = {
                        focusManager.moveFocus(focusDirection = FocusDirection.Next)
                    }),
                    visualTransformation = PasswordVisualTransformation(),
                    decorationBox = {
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(4.dp)
                        ) {
                            if (textWifiPass.value.isEmpty() && !viewModel.wifiPassFocus.collectAsStateWithLifecycle().value) {
                                Text(
                                    text = getString(resourceId = R.string.setting_wifi_pass_hint),
                                    style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary),
                                )
                            } else {
                                it.invoke()
                            }
                        }
                    }
                )
            }

            Divider(color = AppTheme.colors.divider, thickness = 1.dp)
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(intrinsicSize = IntrinsicSize.Min)
                    .padding(16.dp),
                verticalAlignment = CenterVertically
            ) {
                Text(
                    text = getString(resourceId = R.string.setting_wifi_target),
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.width(80.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                BasicTextField(
                    value = textWifiIp1.value,
                    singleLine = true,
                    onValueChange = {
                        scope.launch {
                            if (it.length <= 3) {
                                if(it.contains("."))
                                    return@launch
                                viewModel.wifiIp1.emit(it)
                                if (it.length == 3) {
                                    focusManager.moveFocus(focusDirection = FocusDirection.Next)
                                }
                            }
                        }
                    },
                    textStyle = TextStyle.Default.copy(textAlign = TextAlign.Center),
                    modifier = Modifier
                        .weight(1f),
                    keyboardOptions = KeyboardOptions.Default.copy(
                        keyboardType = KeyboardType.Number,
                        imeAction = ImeAction.Next
                    ),
                    keyboardActions = KeyboardActions(onNext = {
                        focusManager.moveFocus(focusDirection = FocusDirection.Next)
                    }),
                    decorationBox = {
                        Column(modifier = Modifier.fillMaxSize()) {
                            it.invoke()
                            Spacer(modifier = Modifier.height(4.dp))
                            Divider()
                        }
                    }
                )
                Text(
                    text = ".", modifier = Modifier
                        .padding(start = 4.dp, end = 4.dp)
                        .alignByBaseline()
                )
                BasicTextField(
                    value = textWifiIp2.value,
                    singleLine = true,
                    onValueChange = {
                        scope.launch {
                            if (it.length <= 3) {
                                if(it.contains("."))
                                    return@launch
                                viewModel.wifiIp2.emit(it)
                                if (it.length == 3) {
                                    focusManager.moveFocus(focusDirection = FocusDirection.Next)
                                }
                            }
                        }
                    },
                    textStyle = TextStyle.Default.copy(textAlign = TextAlign.Center),
                    modifier = Modifier
                        .weight(1f),
                    keyboardOptions = KeyboardOptions.Default.copy(
                        keyboardType = KeyboardType.Number,
                        imeAction = ImeAction.Next
                    ),
                    keyboardActions = KeyboardActions(onNext = {
                        focusManager.moveFocus(focusDirection = FocusDirection.Next)
                    }),
                    decorationBox = {
                        Column(modifier = Modifier.fillMaxSize()) {
                            it.invoke()
                            Spacer(modifier = Modifier.height(4.dp))
                            Divider()
                        }
                    }
                )
                Text(
                    text = ".", modifier = Modifier
                        .padding(start = 4.dp, end = 4.dp)
                        .alignByBaseline()
                )
                BasicTextField(
                    value = textWifiIp3.value,
                    singleLine = true,
                    onValueChange = {
                        scope.launch {
                            if (it.length <= 3) {
                                viewModel.wifiIp3.emit(it)
                                if (it.length == 3) {
                                    focusManager.moveFocus(focusDirection = FocusDirection.Next)
                                }
                            }
                        }
                    },
                    textStyle = TextStyle.Default.copy(textAlign = TextAlign.Center),
                    modifier = Modifier
                        .weight(1f),
                    keyboardOptions = KeyboardOptions.Default.copy(
                        keyboardType = KeyboardType.Number,
                        imeAction = ImeAction.Next
                    ),
                    keyboardActions = KeyboardActions(onNext = {
                        focusManager.moveFocus(focusDirection = FocusDirection.Next)
                    }),
                    decorationBox = {
                        Column(modifier = Modifier.fillMaxSize()) {
                            it.invoke()
                            Spacer(modifier = Modifier.height(4.dp))
                            Divider()
                        }
                    }
                )
                Text(
                    text = ".", modifier = Modifier
                        .padding(start = 4.dp, end = 4.dp)
                        .alignByBaseline()
                )
                BasicTextField(
                    value = textWifiIp4.value,
                    singleLine = true,
                    onValueChange = {
                        scope.launch {
                            if (it.length <= 3) {
                                if(it.contains("."))
                                    return@launch
                                viewModel.wifiIp4.emit(it)
                                if (it.length == 3) {
                                    focusManager.clearFocus()
                                }
                            }
                        }
                    },
                    textStyle = TextStyle.Default.copy(textAlign = TextAlign.Center),
                    modifier = Modifier
                        .weight(1f),
                    keyboardOptions = KeyboardOptions.Default.copy(
                        keyboardType = KeyboardType.Number,
                        imeAction = ImeAction.Done
                    ),
                    keyboardActions = KeyboardActions(onDone = {
                        focusManager.clearFocus()
                    }),
                    decorationBox = {
                        Column(modifier = Modifier.fillMaxSize()) {
                            it.invoke()
                            Spacer(modifier = Modifier.height(4.dp))
                            Divider()
                        }
                    }
                )
            }
            Divider(color = AppTheme.colors.divider, thickness = 1.dp)
            Spacer(modifier = Modifier.height(16.dp))
            Row(
                modifier = Modifier.clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() },
                    onClick = {
                        isWifiHistoryFlag.value = true
                    })
            ) {
                Text(
                    text = getString(resourceId = R.string.setting_wifi_history),
                    style = TextStyle.Default.copy(color = AppTheme.colors.primaryBtnBg),
                    modifier = Modifier.weight(1f).align(CenterVertically),
                    textAlign = TextAlign.Right,
                    textDecoration = TextDecoration.Underline,
                )
                Image(
                    painter = painterResource(id = R.mipmap.ic_into_blue),
                    contentDescription = "",
                    modifier = Modifier.align(CenterVertically)
                )
            }
            ActionDialogCompose({
                onCancelClick.invoke()
            }) {
                scope.launch {
                    var saveJob = viewModel.saveWifiInfo()
                    var ret = saveJob.await()
                    if (!ret.isNullOrEmpty()) {
                        onWifiUpdateClick()
                        onCancelClick()
                        viewModel.resetUiState()
                    }
                }
            }
            if(isWifiHistoryFlag.value){
                WifiHistoryDialog(isWifiHistoryFlag,onWifiUpdateClick){it->
                    isWifiHistoryFlag.value = false
                    scope.launch {
                        viewModel.wifiName.emit(it.wifiName)
                        viewModel.wifiPass.emit(it.wifiPass)
                        var ipAddress = it.wifiAddress.split(".")
                        viewModel.wifiIp1.emit(ipAddress[0])
                        viewModel.wifiIp2.emit(ipAddress[1])
                        viewModel.wifiIp3.emit(ipAddress[2])
                        viewModel.wifiIp4.emit(ipAddress[3])
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DialogLikeBottomSheet(
    showState: MutableState<Boolean>,
    dismissRequest: () -> Unit = {},
    shape: Shape = BottomSheetDefaults.ExpandedShape,
    dragHandle: (@Composable () -> Unit)? = null,
    content: @Composable (dismissRequest: () -> Unit) -> Unit
) {
    if (showState.value) {
        val transitionState = remember {
            MutableTransitionState(false).apply { targetState = true }
        }
        val scope = rememberCoroutineScope()
        val localDismiss = {
            transitionState.targetState = false
            scope.launch {
                //关闭添加延时，不然太快了关闭动画还没执行完
                delay(200)
                dismissRequest.invoke()
                //重置成默认状态
                transitionState.targetState = true
            }
        }
        Dialog(
            onDismissRequest = {
                localDismiss.invoke()
            },
            properties = DialogProperties(usePlatformDefaultWidth = false)
        ) {
            val dialogWindowProvider = LocalView.current.parent as DialogWindowProvider
            dialogWindowProvider.window.setGravity(Gravity.BOTTOM)
            //默认动画太慢了是500毫秒修改成100
            val animate = tween<IntOffset>(200)
            AnimatedVisibility(
                visibleState = transitionState,
                enter = slideInVertically(initialOffsetY = { it }, animationSpec = animate),
                exit = slideOutVertically(targetOffsetY = { it }, animationSpec = animate)
            ) {
                Surface(shape = shape) {
                    Column {
                        if (dragHandle != null) dragHandle()
                        content(localDismiss)
                    }
                }
            }
        }
    }
}